package com.nova.android.tvlauncher.ui.dialog

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.Gravity
import android.view.KeyEvent
import android.view.ViewGroup
import androidx.core.graphics.drawable.toDrawable
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.bean.atv_bean.KeyBoardDto
import com.nova.android.tvlauncher.databinding.DialogCusKeyboardBinding
import com.nova.android.tvlauncher.databinding.ItemCusKeyboardBinding
import com.nova.android.tvlauncher.ui.dialog.base.BaseDialogFragment
import com.nova.android.tvlauncher.ui.view.CustomEditText
import com.nova.android.tvlauncher.utils.keyboard.KeyBoardHelper
import com_github_lib_base.ext.rv.models
import com_github_lib_base.ext.rv.setup

/**
 * KeyboardDialog：基于你的旧实现改造，直接复用 DialogCusKeyboardBinding 布局
 * 1) 支持 bindEditText(edit) 直接绑定 CustomEditText
 * 2) 内部处理输入/删除/空格/左右光标/大小写/符号切换等逻辑
 * 3) 兼容 TV KeyEvent（重写 handleKeyEvent）
 */
class KeyboardDialog : BaseDialogFragment<DialogCusKeyboardBinding>() {

    override val dialogWidth: Int = ViewGroup.LayoutParams.MATCH_PARENT
    override val dialogGravity: Int = Gravity.BOTTOM
    override val dialogBackground: Drawable = Color.TRANSPARENT.toDrawable()
    override val dialogDimAmount: Float = 0f
    // 可由外部在 showKeyBoardDialog { bindEditText(...) } 内设置
    private var targetEditText: CustomEditText? = null


    // 当前键盘数据
    private lateinit var keyBoardDtos: MutableList<KeyBoardDto>
    private var isUpper = false

    /** 外部调用绑定 EditText（保持你原有调用方式） */
    fun bindEditText(editText: CustomEditText) {
        targetEditText = editText
    }

    override fun initView(savedInstanceState: Bundle?) {

        binding.container.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS

        // 延迟执行，等系统分配完焦点后清除
        binding.container.post {
            binding.container.clearFocus()
            binding.container.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS
        }

        // 初始化数据：复用你之前的逻辑（小写默认）
        keyBoardDtos = KeyBoardHelper.addLowerCase(false)

        // 数字区
        binding.rvNumber.apply {

            val gridLayoutManager = GridLayoutManager(context, 3)
            layoutManager = gridLayoutManager
            setup(KeyBoardHelper.addNumChar()) {
                addType(KeyBoardDto::class, R.layout.item_cus_keyboard)
                onBind {
                    val itemBinding = getBinding<ItemCusKeyboardBinding>()
                    val item = getModel<KeyBoardDto>()
                    itemBinding.tvKeyboard.text = item.keyboardChar
                    itemBinding.ivKeyboard.isVisible = item.keyboardIcon!=null
                    item.keyboardIcon?.let { itemBinding.ivKeyboard.setImageResource(it) }

                    itemView.setOnClickListener {
                        when (item.keyboardType) {
                            KeyBoardDto.KEYBOARD_TYPE_NUM -> inputChangeAction(
                                item.keyboardChar ?: ""
                            )
                        }
                    }
                }
            }

        }

        // 字母/符号区
        binding.rvLetter.apply {
            val gridLayoutManager = GridLayoutManager(context, 9)
            layoutManager = gridLayoutManager
            itemAnimator = null
            setup(keyBoardDtos) {
                addType(KeyBoardDto::class, R.layout.item_cus_keyboard)
                onBind {
                    val itemBinding = getBinding<ItemCusKeyboardBinding>()
                    val item = getModel<KeyBoardDto>()

                    itemBinding.tvKeyboard.text = item.keyboardChar
                    itemBinding.ivKeyboard.isVisible = item.keyboardIcon!=null
                    item.keyboardIcon?.let { itemBinding.ivKeyboard.setImageResource(it) }

                    itemView.setOnClickListener {
                        when (item.keyboardType) {
                            KeyBoardDto.KEYBOARD_TYPE_LETTER,
                            KeyBoardDto.KEYBOARD_TYPE_HALF_CHAR -> {
                                inputChangeAction(item.keyboardChar ?: "")
                            }

                            KeyBoardDto.KEYBOARD_TYPE_SWITCH_Special_Characters -> {
                                keyBoardDtos = KeyBoardHelper.addHalfWidth()
                                this@apply.models = keyBoardDtos as MutableList<Any>
                                binding.rvLetter.post { binding.rvLetter.requestFocus() }
                            }

                            KeyBoardDto.KEYBOARD_TYPE_CASE -> {
                                isUpper = !isUpper
                                KeyBoardHelper.switchLowerUpper(
                                    models as MutableList<KeyBoardDto>,
                                    isUpper
                                ) { pos ->
                                    this@apply.adapter?.notifyItemChanged(pos)
                                }
                            }

                            KeyBoardDto.KEYBOARD_TYPE_DEL -> {
                                charDeleteAction()
                            }

                            KeyBoardDto.KEYBOARD_TYPE_OK -> {
                                // 完成：隐藏 dialog 并触发 confirm 回调（如需要）
                                dismiss()
                                invokeConfirmAction()
                            }

                            KeyBoardDto.KEYBOARD_TYPE_SPACE -> {
                                inputSpaceAction()
                            }

                            KeyBoardDto.KEYBOARD_TYPE_LEFT_ARROW -> {
                                leftArrowAction()
                            }

                            KeyBoardDto.KEYBOARD_TYPE_RIGHT_ARROW -> {
                                rightArrowAction()
                            }

                            KeyBoardDto.KEYBOARD_TYPE_BACK_LETTER -> {
                                keyBoardDtos = KeyBoardHelper.addLowerCase(isUpper)
                                this@apply.models = keyBoardDtos as MutableList<Any>
                                binding.rvLetter.post { binding.rvLetter.requestFocus() }
                            }
                        }
                    }
                }
            }

        }

        // 初始 focus
        binding.rvLetter.post { binding.rvLetter.requestFocus() }
    }

    // 使用 BaseDialogFragment 的 onStart 已处理 window 参数（如果你想覆盖可修改 dialogBackground / dialogWidth 等）
    override fun onStart() {
        super.onStart()
        // 保持透明背景（你原来是透明的）
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        // 清掉之前的默认焦点
        binding.rvNumber.clearFocus()

        // 直接请求右边 RecyclerView 焦点
        binding.rvLetter.requestFocusFromTouch()
    }

    // 帮助函数：插入字符
    private fun inputChangeAction(text: String) {
        val et = targetEditText ?: return
        val editable = et.text ?: return
        val start = et.selectionStart.coerceAtLeast(0)
        editable.insert(start, text)
        et.setSelection(start + text.length)
    }

    // 删除（向前删除一个字符）
    private fun charDeleteAction() {
        val et = targetEditText ?: return
        val editable = et.text ?: return
        val start = et.selectionStart
        if (start > 0) {
            editable.delete(start - 1, start)
            et.setSelection(start - 1)
        }
    }

    // 空格
    private fun inputSpaceAction() {
        inputChangeAction(" ")
    }

    // 左移光标
    private fun leftArrowAction() {
        val et = targetEditText ?: return
        val pos = et.selectionStart
        if (pos > 0) et.setSelection(pos - 1)
    }

    // 右移光标
    private fun rightArrowAction() {
        val et = targetEditText ?: return
        val pos = et.selectionStart
        val len = et.text?.length ?: 0
        if (pos < len) et.setSelection(pos + 1)
    }

    /**
     * 初始化 GridLayoutManager 的 spanSizeLookup（复用你原逻辑）
     */
    private fun initLayoutManager() {
        val gridLayoutManager = binding.rvLetter.layoutManager as? GridLayoutManager ?: return
        gridLayoutManager.spanSizeLookup = object : SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                val item = keyBoardDtos[position]
                return when {
                    item.keyboardType == KeyBoardDto.KEYBOARD_TYPE_OK -> 2
                    item.keyboardType == KeyBoardDto.KEYBOARD_TYPE_SWITCH_Special_Characters -> 2
                    item.keyboardType == KeyBoardDto.KEYBOARD_TYPE_SPACE -> 2
                    else -> 1
                }
            }
        }
    }

    /**
     * 重写 BaseDialogFragment 的按键处理（TV 方向/确认/删除）
     * BaseDialogFragment 的 setupKeyListener 会在 onViewCreated 时注册
     */
    override fun handleKeyEvent(keyCode: Int, event: KeyEvent): Boolean {
        if (event.action != KeyEvent.ACTION_UP) return false
        // 如果是可打印字符（android 事件里 displayLabel），则插入
        val hasChar = event.unicodeChar != 0
        return if (!hasChar) {
            when (keyCode) {
                KeyEvent.KEYCODE_DEL -> {
                    charDeleteAction(); true
                }

                else -> false
            }
        } else {
            when (keyCode) {
                KeyEvent.KEYCODE_SPACE -> {
                    inputSpaceAction(); true
                }

                else -> {
                    // displayLabel 可能为单字符
                    val ch = event.displayLabel.toString()
                    if (ch.isNotEmpty()) {
                        inputChangeAction(ch)
                        true
                    } else false
                }
            }
        }
    }
}
